/**
 * LogoutDialog component
 * @module components/root/LogoutDialog
 */
// import packages
import React, { useCallback, useState } from "react";
import {
  Dialog,
  DialogActions,
  DialogTitle,
  Button,
  Box,
  TextField,
  DialogContent,
  Typography,
  IconButton,
  Select,
  MenuItem,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";

// import libary
import {
  PublishDepartment,
  Valid,
  SelectTextFiled,
  DatePicker,
  fullText,
  EffectivenessLevel,
  validateDates,
} from "./Common";
import { LilySnack } from "../common/Common";

/**
 * AdvancedSearchDialog component
 * @function LogoutDialog
 * @static
 * @returns {component} AdvancedSearchDialog
 */
export default function AdvancedSearchDialog({
  openAdvancedSearchDialog,
  setOpenAdvancedSearchDialog,
  handleCloseAdvancedSearchDialog,
  setSearchData,
}) {
  /* ---------------------------------------------------------
   *                    Snackbar messages
   * ---------------------------------------------------------*/
  const [snackbarMes, setSnackbarMes] = useState({
    text: undefined,
    open: false,
    severity: "warning",
  });

  //点击背景或者Esc关闭对话框
  const closeAdvancedSearchDialog = useCallback((e, reason) => {
    if (reason === "escapeKeyDown" || reason === "backdropClick") {
      setOpenAdvancedSearchDialog(false);
    }
  }, []);

  /* -----------------------------------------------------
   *                   Search data
   * -----------------------------------------------------*/

  const [data, setData] = useState({
    publishStartDate: "1949-10-01", // 设置默认开始日期为1949年10月1日
    publishEndDate: new Date().toISOString().split('T')[0], // 设置默认结束日期为当前日期
    keywords: "",
    isValid: Valid[0]?.label || "不限", // 如果没有值，设置为默认值 '不限'
    publishDepartment: PublishDepartment[0]?.label || "不限", // 同样处理
    fullText: fullText[0]?.label || "不限", // 同样处理
    effectivenessLevel: EffectivenessLevel[0]?.label || "不限", // 同样处理
  });

  /**
   * 清空搜索条件
   * @param {*} e
   */
  const handleClearSearchData = () => {
    setData({
      publishStartDate: "1949-10-01", // 设置默认开始日期为1949年10月1日
      publishEndDate: new Date().toISOString().split('T')[0], // 设置默认结束日期为当前日期
      keywords: "",
      isValid: Valid[0].label,
      publishDepartment: PublishDepartment[0].label,
      fullText: fullText[0].label,
      effectivenessLevel: EffectivenessLevel[0]?.label || "不限", // 同样处理
    });
  };
  
  //进行处理搜索
  //TODO做一个保存草稿的功能
  const handleConfirmSearch = async (e) => {
    //进行非空验证
    //TODO 有效性检查
    e.preventDefault(); // 阻止表单默认提交行为

    // 检查日期有效性
    const dateError = validateDates(data.publishStartDate, data.publishEndDate);
    if (dateError) {
      setSnackbarMes({
        text: dateError,
        open: true,
        severity: "error",
      });
      return; // 如果日期无效，不执行后续代码
    }
    // 检查是否所有字段都为空
    const isAllFieldsEmpty =
      !data.publishStartDate &&
      !data.publishEndDate &&
      data.fullText === fullText[0].label &&
      data.publishDepartment === PublishDepartment[0].label &&
      data.effectivenessLevel === EffectivenessLevel[0].label &&
      data.isValid === Valid[0].label;

    // 检查关键字是否为空
    const isKeywordEmpty = data.keywords === "";

    if (isAllFieldsEmpty || isKeywordEmpty) {
      if (isAllFieldsEmpty) {
        setSnackbarMes({
          text: "请输入正确的搜索条件！",
          open: true,
          severity: "error",
        });
      } else if (isKeywordEmpty) {
        setSnackbarMes({
          text: "关键字不能为空！",
          open: true,
          severity: "error",
        });
      }
      return; // 如果任一条件为真，则不执行后续代码
    }

    //关闭对话框
    handleCloseAdvancedSearchDialog();
    e.preventDefault();
    setSearchData(data);
    handleClearSearchData(); //检索之后清空条件
  };

  return (
    <Dialog
      maxWidth="md" // 限制最大宽度为屏幕宽度的一半
      fullWidth={true} // 使 Dialog 宽度尽可能大，但不超过 maxWidth
      open={openAdvancedSearchDialog}
      onClose={closeAdvancedSearchDialog}
    >
      <DialogTitle align="center">高级搜索</DialogTitle>
      <IconButton
        aria-label="close"
        onClick={handleCloseAdvancedSearchDialog}
        sx={{
          position: "absolute",
          right: 8,
          top: 8,
          color: (theme) => theme.palette.grey[500],
        }}
      >
        <CloseIcon />
      </IconButton>
      {/** 内容区域*/}
      <DialogContent dividers>
        <form onSubmit={handleConfirmSearch}>
          <Box sx={{ mt: "15px", display: "flex", alignItems: "center" }}>
            <Typography variant="body1" noWrap sx={{ minWidth: "85px" }}>
              关键字
            </Typography>
            <Select
              sx={{ width: 100, ml: 2 }} // 设置下拉菜单的宽度
              size="small"
              value={data.fullText}
              onChange={(e) => setData({ ...data, fullText: e.target.value })}
            >
              {fullText.map((option) => (
                <MenuItem key={option.label} value={option.label}>
                  {option.label}
                </MenuItem>
              ))}
            </Select>
            <TextField
              fullWidth
              id="key-word"
              label="请输入关键字"
              type="text"
              size="small"
              sx={{ ml: 2 }} // 添加左侧间距
              value={data.keywords}
              onChange={(e) => setData({ ...data, keywords: e.target.value })}
            />
          </Box>
          <SelectTextFiled
            title={"发布部门"}
            id={"publish-department-select"}
            label={"选择部门"}
            options={PublishDepartment}
            value={data.publishDepartment}
            onChange={(e) => setData({ ...data, publishDepartment: e.target.value })}
          />
          {/**
           * 不知道为什么效力位阶的select有警告，说value可能为undefined
           */}
          <SelectTextFiled
            title={"效力级别"}
            id={"effectiveness-level-select"}
            label={"选择级别"}
            options={EffectivenessLevel}
            value={data.effectivenessLevel}
            onChange={(e) => setData({ ...data, effectivenessLevel: e.target.value })}
          />
          <DatePicker
            title={"发布日期"}
            id={"publishAt"}
            startDate={data.publishStartDate}
            endDate={data.publishEndDate}
            handlePublishStartDateChange={(e) => setData({ ...data, publishStartDate: e.target.value })}
            handlePublishEndDateChange={(e) => setData({ ...data, publishEndDate: e.target.value })}
          />
          {/* <DatePicker title={"实施日期"} id={"ImplementationAt"} /> */}
          <SelectTextFiled
            title={"有效性"}
            id={"valid-select"}
            label={"选择有效性"}
            options={Valid}
            value={data.isValid}
            onChange={(e) => setData({ ...data, isValid: e.target.value })}
          />
        </form>
      </DialogContent>
      <DialogActions
        sx={{
          display: "flex",
          flexFlow: "row nowrap",
          justifyContent: "space-around",
        }}
      >
        <Button onClick={handleConfirmSearch} autoFocus>
          立即搜索
        </Button>
        <Button onClick={handleClearSearchData}>清空条件</Button>
      </DialogActions>
      <LilySnack
        duration={snackbarMes.duration}
        open={snackbarMes.open}
        onClose={(event, reason) => {
          if (reason === "clickaway") {
            return;
          }
          setSnackbarMes({ ...snackbarMes, open: false });
        }}
        severity={snackbarMes.severity}
        text={snackbarMes.text}
      />
    </Dialog>
  );
}
